package priv.lhy.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * author : lihy
 * date : 2019/1/22 15:15
 * <p>
 * json工具类
 */
public class JsonUtils {

    private static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);
    private static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
        //时间格式
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * JSON串转换为java泛型对象，主要解决List，Map等集合的转换
     *
     * @param jsonStr JSON字符串
     * @param tr      TypeReference 泛型类型，例如：new TypeReference<List<Object> >(){}
     * @param <T>     List对象列表
     * @return
     */
    public static <T> T json2GenericObject(String jsonStr, TypeReference<T> tr) {
        if (jsonStr != null && !jsonStr.isEmpty()) {
            try {
                //有属性不能映射成PO时不报错
                OBJECT_MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                return (T) OBJECT_MAPPER.readValue(jsonStr, tr);
            } catch (IOException e) {
                LOG.error("json error: " + e.getMessage());
            }
        }
        return null;
    }

    /**
     * java对象转JSON字符串
     *
     * @param object java对象，可以是对象、数组、List、Map等
     * @return JSON字符串
     */
    public static String toJson(Object object) {
        String jsonStr = "";
        try {
            jsonStr = OBJECT_MAPPER.writeValueAsString(object);
        } catch (IOException e) {
            LOG.error("json error: " + e.getMessage());
        }
        return jsonStr;
    }

    /**
     * JSON字符串转java对象
     *
     * @param jsonStr JSON字符串
     * @param clazz   对象类型
     * @return
     */
    public static Object json2Object(String jsonStr, Class<?> clazz) {
        if (jsonStr != null && !jsonStr.isEmpty()) {
            try {
                return OBJECT_MAPPER.readValue(jsonStr, clazz);
            } catch (IOException e) {
                LOG.error("json error: " + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 根据JSON字符串和节点名称返回节点
     *
     * @param jsonStr  JSON字符串
     * @param nodeName 节点名称
     * @return
     */
    public static JsonNode getNode(String jsonStr, String nodeName) {
        JsonNode node = null;
        try {
            node = OBJECT_MAPPER.readTree(jsonStr);
            return node.get(nodeName);
        } catch (IOException e) {
            LOG.error("json error: " + e.getMessage());
        }
        return node;
    }

    /**
     * JsonNode转换为java泛型对象，可以是各种类型，主要解决List，Map等集合的转换
     *
     * @param node Json节点
     * @param tr    TypeReference 泛型类型，例如：new TypeReference<List<Object> >(){}
     * @param <T> List对象列表
     * @return
     */
    public static <T> T jsonNode2GenericObject(JsonNode node, TypeReference<T> tr) {
        if (node != null) {
            try {
                return OBJECT_MAPPER.readValue(node, tr);
            } catch (IOException e) {
                LOG.error("json error: " + e.getMessage());
            }
        }
        return null;
    }


    /**
     * 根据JSON字符串获取某个字段的值
     *
     * @param jsonStr   JSON字符串
     * @param paramName 字段名称
     * @return
     */
    public static String getValueFromJsonStr(String jsonStr, String paramName) {
        if (StringUtils.isNotBlank(jsonStr) && StringUtils.isNotBlank(paramName)) {
            try {
                JSONObject obj = JSONObject.parseObject(jsonStr);
                if (obj != null) {
                    return obj.getString(paramName);
                }
            } catch (Exception e) {
                LOG.error("get param[" + paramName + "] value from json[" + jsonStr + "] error: " + e);
            }
        }
        return null;
    }

}
